package com.pipayshop.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;

/**
 * @author wzx
 */
@Configuration
@EnableTransactionManagement
public class AppConfig {
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;


    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        // 设置连接池的配置参数
        dataSource.setInitialSize(5);        // 初始连接数
        dataSource.setMinIdle(5);            // 最小空闲连接数
        dataSource.setMaxActive(20);         // 最大连接数
        dataSource.setMaxWait(60000);        // 获取连接的最大等待时间
        dataSource.setTimeBetweenEvictionRunsMillis(60000); // 空闲连接检测间隔
        dataSource.setMinEvictableIdleTimeMillis(300000);    // 最小空闲时间

        return dataSource;
    }


    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}
